package com.doudou.oauth.handler;

import com.doudou.commons.utils.BrowserUtils;
import com.doudou.oauth.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 傻男人
 * @Date: 2020/5/8 16:26
 * @Version: 1.0
 * @Description: 用户未登录时的处理
 */
@Slf4j
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        try {
            if(BrowserUtils.isBrowser(request)){
                log.info("-----引发跳转的url:  "+ request.getRequestURL());
                String url = request.getRequestURI();

                RequestCache cache = new HttpSessionRequestCache();
                cache.saveRequest(request,response);
                response.sendRedirect(SysConstant.DEFAULT_LOGIN_PAGE_URL);
            }
            return;
        } catch (IOException e) {
            throw new ServletException();
        }
    }
}